package org.masterinftel.scrumpmt.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.masterinftel.scrumpmt.Constants;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class UtilNetwork {
	// Cliente para realizar peticiones REST
	private static DefaultHttpClient client = new DefaultHttpClient();

	public static JsonReader insertJSON(String urlRest, Object json) {
		HttpPost postRequest = new HttpPost(urlRest);
		JsonReader reader = null;
		try {
			String jsonString = new Gson().toJson(json);
			StringEntity se = new StringEntity(jsonString,
					HTTP.UTF_8);

			se.setContentType("application/json");
			postRequest.setHeader("Content-Type",
					"application/json;charset=UTF-8");
			postRequest.setEntity(se);
			HttpResponse getResponse = client.execute(postRequest);
			HttpEntity getResponseEntity = getResponse.getEntity();
			InputStream is = getResponseEntity.getContent();
			reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
		} catch (IOException e) {
			postRequest.abort();
			Log.w(Constants.LOGTAG, "Error for URL " + urlRest, e);
		}
		return reader;
	}

	public static JsonReader getJSON(String url) {
		HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w(Constants.LOGTAG, "Error " + statusCode + " for URL "
						+ url);
				return null;
			}
			HttpEntity getResponseEntity = getResponse.getEntity();
			InputStream is = getResponseEntity.getContent();
            return new JsonReader(new InputStreamReader(is, "UTF-8"));
		} catch (IOException e) {
			getRequest.abort();
			Log.w(Constants.LOGTAG, "Error for URL " + url, e);
		}
		return null;
	}
}
